package com.zhen.aikan.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.zhen.aikan.constant.RedisConstants;
import com.zhen.aikan.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author LiJiaZhen
 * @date 2023/9/22 14:27
 */
@Component
public class RedisUtils {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static StringRedisTemplate staticStringRedisTemplate;
    @PostConstruct
    protected void init(){
        staticStringRedisTemplate = stringRedisTemplate;
    }
    public static Map<String, Object> setUserMap(User user, String token){
        Map<String, Object> userMap = BeanUtil.beanToMap(user, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreError(false)
                        .setIgnoreNullValue(false)
                        .setFieldValueEditor((fieldName, fieldValue) -> {
                            if(fieldValue == null){
                                return null;
                            }
                            return fieldValue.toString();
                        }));
        staticStringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,userMap);
        //设置过期时间
        staticStringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY+token,RedisConstants.LOGIN_USER_TTL, TimeUnit.DAYS);
        return userMap;
    }
}
